﻿@if (menuListAll == null)
{
     <Spin size="SpinSize.Large" Tip="Loading..." />
}
else
{
    <Menu DefaultSelectedKeys=@(new[] { defaultSelectedKeys })
          DefaultOpenKeys=@(new[] { defaultOpenKeys })
          Mode=MenuMode.Inline
          Theme=MenuTheme.Dark
          InlineCollapsed=collapsed>

        @renderFragmentMenu(menuListAll)

    </Menu>
}

@inject SysMenuService dataService

@code {

    [CascadingParameter]
    public Error? Error { get; set; }

    [Parameter]
    public bool collapsed { get; set; }

    string defaultSelectedKeys = "";
    string defaultOpenKeys = "";
    List<SysMenu> menuListAll;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            menuListAll ??= await dataService.GetToTreeCacheAsync();
            defaultSelectedKeys = menuListAll.FirstOrDefault()?.Id.ToString();
            defaultOpenKeys = menuListAll.Where(a => a.Children.Any()).FirstOrDefault()?.Name;

        }
        catch (Exception ex)
        {
            Error?.ProcessError(ex);
        }
    }

    private RenderFragment renderFragmentMenu(IEnumerable<SysMenu> sysMenus)
    {
        return builder =>
        {
            @foreach (var item in sysMenus)
            {
                builder.OpenComponent(0, typeof(RecursionMenuItem));
                builder.AddAttribute(1, "menu", item);
                builder.AddAttribute(2, "ChildContent", renderFragmentMenu(item.Children));
                builder.CloseComponent();
            }
        };
    }


}
